﻿using System.Collections.Concurrent;
using System.Collections.Generic;
using Fetches.Fetch.Factory.Persistence;

namespace FetchesDeploy.Distributed.Factory.Mapping
{
    public class FetcherType2Unit
    {
        /// <summary>
        ///     Fetcher类型到Unit的映射
        /// </summary>
        private readonly ConcurrentDictionary<string, IList<UnitSchedules>> _fetcherType2Unit =
            new ConcurrentDictionary<string, IList<UnitSchedules>>();

        public void RegisterUnit(UnitSchedules unit)
        {
            foreach (var fetcherType in unit.SupportedFetcherTypes)
            {
                if (!_fetcherType2Unit.TryGetValue(fetcherType, out var workshops))
                {
                    workshops = new List<UnitSchedules>();
                    _fetcherType2Unit.TryAdd(fetcherType, workshops);
                }

                workshops.Add(unit);
            }
        }

        /// <summary>
        /// 移除支持关系的注册
        /// </summary>
        /// <param name="unit"></param>
        public void UnRegisterUnit(UnitSchedules unit)
        {
            foreach (var supportedFetcherType in unit.SupportedFetcherTypes)
            {
                _fetcherType2Unit.TryGetValue(supportedFetcherType, out var workshops);
                workshops?.Remove(unit);
            }
        }

        public IList<UnitSchedules> SelectSupportedUnit(string fetcherType)
        {
            if (_fetcherType2Unit.TryGetValue(fetcherType, out IList<UnitSchedules> unitList))
            {
                return unitList;
            }

            return null;
        }
    }
}
